<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>模板管理</title>
    <!-- Bootstrap CSS-->
    <link rel="stylesheet" href="../../static/css/lib/bootstrap3.4.1.min.css" th:href="@{/css/lib/bootstrap3.4.1.min.css}">
    <!-- Bootstrap-table CSS-->
    <link rel="stylesheet" href="../../static/css/lib/bootstrap-table.min.css" th:href="@{/css/lib/bootstrap-table.min.css}">
    <!-- jquery-ui CSS-->
    <link rel="stylesheet" href="../../static/css/lib/jquery-ui.min.css" th:href="@{/css/lib/jquery-ui.min.css}">
    <!-- fileinput CSS-->
    <link rel="stylesheet" href="../../static/css/lib/fileinput.min.css" th:href="@{/css/lib/fileinput.min.css}">
    <link href="../../static/css/file.css" rel="stylesheet" th:href="@{/css/file.css}">
    <link href="../../static/css/table.css" rel="stylesheet" th:href="@{/css/table.css}">
</head>

<body onload="init();">

    <div class="panel-body" style="padding-bottom:0;">
        <div class="panel panel-default">
            <div class="panel-heading">查询条件</div>
            <div class="panel-body">
                <div class="form-group" style="margin-top:15px">
                    <div class="row row-gap">
                        <label class="control-label col-sm-2 label-font" for="txt_search_start_time">开始时间</label>
                        <div class="col-sm-4">
                            <input type="datetime-local" class="form-control" id="txt_search_start_time">
                        </div>

                        <label class="control-label col-sm-2 label-font" for="txt_search_end_time">结束时间</label>
                        <div class="col-sm-4">
                            <input type="datetime-local" class="form-control" id="txt_search_end_time">
                        </div>
                    </div>
                    <div class="row row-gap">
                        <label class="control-label col-sm-2 label-font" for="txt_search_name">模板名称</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="txt_search_name">
                        </div>
                    </div>
                    <div class="row row-gap">
                        <div class="col-sm-offset-4" style="text-align:left;">
                            <button type="button" style="margin-left:50px" id="btn_filter" class="btn btn-primary" onclick="filter();">过滤</button>
                            <button type="button" style="margin-left:50px" id="btn_reset_filter" class="btn btn-primary" onclick="init();">重置过滤</button>
                        </div>
                    </div>

                </div>
            </div>
        </div>
        <div id="toolbar" class="btn-group">
            <button id="btn_add" type="button" class="btn btn-default" data-toggle="modal" data-target="#addModal">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>上传模板
            </button>
        </div>
        <table id="table"></table>
    </div>

    <!--模态框（Modal） 新增-->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
        <div class="modal-dialog " style="min-width: 800px">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title" id="addModalLabel">
                        添加模板信息
                    </h2>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" role="form">
                        <div class="form-group has-error">
                            <label class="col-sm-2 control-label label-font" for="template_type_select">模板类型</label>
                            <div class="col-sm-10">
                                <select class="form-control" id="template_type_select" onchange="addTemplateTypeChange();">
                                </select>
                            </div>
                        </div>
                        <div class="form-group has-success">
                            <label class="col-sm-2 control-label label-font" for="txt_remark">备注</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" rows="6" id="txt_remark"></textarea>
                            </div>
                        </div>
                        <div class="form-group has-success">
                            <label class="col-sm-2 control-label label-font" for="add_import">上传模板</label>
                            <div class="col-sm-10">
                                <button id="add_import" type="button" class="btn btn-default" data-toggle="modal" data-target="#excelModal" disabled onclick="importType = 1;">
                                    <span class="glyphicon glyphicon-import" aria-hidden="true"></span>上传
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div> <!--/.modal-content -->
        </div><!--/.modal-->
    </div>

    <!--模态框（Modal） 编辑-->
    <div class="modal fade" id="alterModal" tabindex="-1" role="dialog" aria-labelledby="alterModalLabel" aria-hidden="true">
        <div class="modal-dialog " style="min-width: 800px">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title" id="alterModalLabel">
                        编辑模板信息
                    </h2>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" role="form">
                        <div class="form-group has-success">
                            <label class="col-sm-2 control-label label-font" for="alter_template_type_select">模板类型</label>
                            <div class="col-sm-10">
                                <select class="form-control" id="alter_template_type_select">
                                </select>
                            </div>
                        </div>
                        <div class="form-group has-success">
                            <label class="col-sm-2 control-label label-font" for="alter_remark">备注</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" rows="6" id="alter_remark"></textarea>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button id="alter_import" type="button" class="btn btn-success" data-toggle="modal" data-target="#excelModal" onclick="importType = 0;">上传</button>
                    <button type="button" class="btn btn-primary" onclick="alter();">编辑</button>
                </div>
            </div> <!--/.modal-content -->
        </div><!--/.modal-->
    </div>

    <!-- 模态框（Modal） 图片上传 -->
    <div class="modal fade" id="excelModal" tabindex="-1" role="dialog" aria-labelledby="excelModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>
                    <h4 class="modal-title" id="excelModalLabel">
                        模板上传
                    </h4>
                </div>
                <div class="modal-body">
                    <form enctype="multipart/form-data">
                        <div class="form-group">
                            <input id="upload" type="file" class="file" name="file">
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>

<!-- JavaScript files-->
<!-- jquery.js -->
<script src="../../static/js/lib/jquery.min.js" th:src="@{/js/lib/jquery.min.js}"></script>
<!-- Bootstrap.js -->
<script src="../../static/js/lib/bootstrap3.4.1.min.js" th:src="@{/js/lib/bootstrap3.4.1.min.js}"></script>
<!-- Bootstrap-table.js -->
<script src="../../static/js/lib/bootstrap-table.min.js" th:src="@{/js/lib/bootstrap-table.min.js}"></script>
<script src="../../static/js/lib/bootstrap-table-zh-CN.min.js" th:src="@{/js/lib/bootstrap-table-zh-CN.min.js}"></script>
<!-- sweetalert2.js -->
<script src="../../static/js/lib/sweetalert.min.js" th:src="@{/js/lib/sweetalert.min.js}"></script>
<script src="../../static/js/lib/es6-promise.auto.min.js" th:src="@{/js/lib/es6-promise.auto.min.js}"></script>
<!-- jquery-ui.js -->
<script src="../../static/js/lib/jquery-ui.min.js" th:src="@{/js/lib/jquery-ui.min.js}"></script>
<!-- fileinput.js -->
<script src="../../static/js/lib/fileinput.min.js" th:src="@{/js/lib/fileinput.min.js}"></script>
<script src="../../static/js/lib/fileinput_locale_zh.js" th:src="@{/js/lib/fileinput_locale_zh.js}"></script>
<script src="../../static/js/common.js" th:src="@{/js/common.js}"></script>
<script src="../../static/js/dragModel.js" th:src="@{/js/dragModel.js}"></script>

<script>
    /** 初始化 */
    let $table = $("#table");
    let $upload = $("#upload");
    let $typeSelect = $("#template_type_select");
    let $alterTypeSelect = $("#alter_template_type_select");
    let importType;
    let alterId;

    // 服务器分页获取数据
    function getServerPaging(node, url, queryParams) {
        initTable(node, url, [10, 20, 30, 40, 50, 60, "All"], queryParams, [{
            checkbox: true
        }, {
            field: 'name',
            title: '模板名称',
            width: '180px',
            formatter: stringFormatter
        }, {
            field: 'typeText',
            title: '模板类型',
            width: '180px',
            formatter: stringFormatter
        }, {
            field: 'url',
            title: '模板路径',
            width: '180px',
            formatter: stringFormatter
        }, {
            field: 'createTime',
            title: '上传日期',
            width: '170px',
            formatter: dateFormatter
        }, {
            field: 'updateTime',
            title: '修改日期',
            width: '170px',
            formatter: dateFormatter
        }, {
            field: 'remark',
            title: '备注',
            width: '180px',
            formatter: stringFormatter
        }, {
            field: 'operation',
            title: '操作',
            width: '257px',
            formatter: operateFormatter // 自定义方法，添加操作按钮
        }]);
    }

    function operateFormatter(value, row, index) {  // 赋予的参数
        return [
            '<button class="btn btn-success view" onclick="load('+ index +');">下载</button>&nbsp;&nbsp;'+
            '<button class="btn btn-primary view" data-toggle="modal" data-target="#alterModal" onclick="initAlter('+ index +');">编辑</button>&nbsp;&nbsp;'+
            '<button class="btn btn-danger view"  onclick="deleteAll('+ index +');">删除</button>'
        ].join('');
    }

    dragTheModalDialog();

    changeToolTip();

    // 增加下拉框初始化
    function initSelect() {
        noParameterPostRequest("/the-data-dictionary/getDict?limit=100&offset=0&sort=create_time&order=DESC&type=templateType", result => {
            $typeSelect.empty();
            $typeSelect.append("<option value='--请选择--'>--请选择--</option>");
            result.module.rows.forEach(item => $typeSelect.append("<option value="+ item.id +">" + item.value + "</option>"));
        }, "GET");
    }

    // 编辑下拉框初始化
    function initAlterSelect() {
        noParameterPostRequest("/the-data-dictionary/getDict?limit=100&offset=0&sort=create_time&order=DESC&type=templateType", result => {
            $alterTypeSelect.empty();
            result.module.rows.forEach(item => $alterTypeSelect.append("<option value="+ item.id +">" + item.value + "</option>"));
        }, "GET");
    }

    // 初始化数据信息
    function init() {
        getServerPaging($table, "/template-management/getTemplate", params => {
            return { limit: params.limit, offset: params.offset, sort: "create_time", order: "DESC" };
        });
        initSelect();
        initAlterSelect();
    }

    // 模板上传
    let filename;
    $upload.fileinput({
        language: 'zh',     // 设置语言
        dropZoneTitle: '可以将模板拖放到这里...',
        uploadUrl: '/file/upload',
        overwriteInitial: false,
        maxFileSize: 10240,      // 单位为kb，如果为0表示不限制文件大小
        minFileCount: 1,        // 每次上传允许的最少文件数。如果设置为0，则表示文件数是可选的。默认为0
        maxFileCount: 1,        // 每次上传允许的最大文件数。如果设置为0，则表示允许的文件数是无限制的。默认为0
        maxFilesNum: 1,
        uploadExtraData: function() {
            return { fileType: "template", fileName: null };
        }
    }).on("filebatchselected", (event, files) => {
        filename = files[0].name;
    }).on("fileuploaded", function(e, data) { // 文件上传成功的回调函数
        if (data.response === null) {
            swal("错误", "不支持该文件类型", "success");
            return;
        }

        if (data.response.success === false) {
            switch (data.response.code) {
                case 9002: swal("错误", "参数错误", "error");     break;
                case 9006: swal("错误", "文件创建错误", "error"); break;
            }
        } else {
            if (1 === importType) {
                let data = {
                    name: filename,
                    dictId: $("#template_type_select").val(),
                    url: filename,
                    remark: $("#txt_remark").val()
                };
                parameterPostRequest("/template-management/insert", data, () => {
                    $('#excelModal').modal('hide');
                    $('#addModal').modal('hide');
                    swal("成功", "模板上传成功", "success");
                    init();
                });
            } else {
                let data = {
                    id: alterId,
                    name: filename,
                    url: filename
                };
                parameterPostRequest("/template-management/updateUrl", data, () => {
                    $('#excelModal').modal('hide');
                    $('#alterModal').modal('hide');
                    swal("成功", "模板上传成功", "success");
                    init();
                });
            }
        }
    });
</script>

<script>
    /** 逻辑功能 */
    let $setInputError = $("#template_type_select");
    let $add_import = $("#add_import");
    function addTemplateTypeChange() {
        if ("--请选择--" === $setInputError.val()) {
            $add_import.attr("disabled", "true");
            setInputError($setInputError);
        } else {
            $add_import.removeAttr("disabled");
            setInputSuccess($setInputError);
        }
    }
</script>

<script>
    /** 功能 */
    // 过滤
    function filter() {
        let time = [$("#txt_search_start_time"), $("#txt_search_end_time")];
        if ("" !== time[0][0].validationMessage || "" !== time[1][0].validationMessage) {
            swal("操作提示", "请填写完整的时间", "info");
            return;
        }
        let data = {
            name : $("#txt_search_name").val(),
            startTime: time[0].val(),
            endTime: time[1].val()
        };
        if ("" === data["name"] && "" === data["startTime"] && "" === data["endTime"]) {
            swal("操作提示", "请填写过滤参数", "info");
            return;
        }
        getServerPaging($table, "/template-management/getTemplate", params => {
            let result = { limit: params.limit, offset: params.offset, sort: "create_time", order: "DESC",
                name: data["name"], startTime: data["startTime"], endTime: data["endTime"] };
            removeEmptyField(result);
            return result;
        });
    }

    // 下载文件
    function load(index) {
        loadFile("template\\" + $table.bootstrapTable('getData')[index].url);
    }

    // 删除
    function deleteAll(index) {
        dialog("确定删除吗？", () => {
            let data = { "id": $table.bootstrapTable('getData')[index].id };
            parameterPostRequest("/template-management/delete", data, () => {
                swal("正确", "删除成功", "success");
                init();
            });
        });
    }

    // 编辑
    function initAlter(index) {
        let rows = $table.bootstrapTable('getData');
        $alterTypeSelect.val(rows[index].dictId);
        $("#alter_remark").val(rows[index].remark);
        alterId = rows[index].id;
    }
    function alter() {
        let data = {
            id: alterId,
            dictId: $("#alter_template_type_select").val(),
            remark: $("#alter_remark").val()
        };
        if ("" === data.dictId) {
            swal("操作提示", "请输入必输入项", "info");
        } else {
            parameterPostRequest("/template-management/updateTemplate", data, () => {
                $('#alterModal').modal('hide');
                swal("正确", "编辑成功", "success");
                init();
            });
        }
    }

</script>

</body>

</html>